var express = require('express');
var http = require('http');
var path = require('path');
var _ = require('lodash');
var ejs = require('ejs');
var logger = require('morgan');
var bodyParser = require('body-parser');
var favicon = require("serve-favicon");
var cookieParser = require('cookie-parser');
var moment = require('moment');
var compression = require('compression');
var routers = require('./routers/index.js');
var config = require('./config.json')[process.env.NODE_ENV || 'development'];
var app = express();

// all environments
app.enabled('trust proxy'); //检查设置项 name 是否已启用

//ejs的相关配置
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.set('view cache', config['view_cache']);
app.use(logger('dev')); //在控制台打印日志
app.use(compression()); //启动Gzip压缩功能，有效的加速了网页内容的加载
app.use(bodyParser.json()); //用于解析客户端请求的body中的内容格式是 application/json
app.use(bodyParser.urlencoded({ //用于解析客户端请求的编码格式     application/x-www-form-urlencoded
  extended: false
}));
app.use(cookieParser()); //使用cookie模块
//设置跨域访问
app.all('*.shtml', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, token");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Access-Control-Allow-Credentials", true);
  res.header("X-Powered-By", '3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

//设置静态资源路径
app.use(config.dir, express.static(path.join(__dirname, 'public/dev')));
app.use(config.dir, express.static(path.join(__dirname, 'public')));
app.use(favicon(__dirname+'/public/img/favicon.jpg'));//设置favicon标题图标
routers(app);
//应用级全局变量：app.locals，设置全局属性
app.locals.moment = moment;
app.locals.moment.locale = 'zh-cn';
app.locals.global = global.global;
app.locals.global_url = "";
app.locals._ = _;
app.locals.setting = global.setting;

//app.dynamicHelpers
app.use(function(req, res, next) {
  //响应级全局变量：res.locals
  res.locals.session = req.session;
  global.token = req.headers.token;
  next();
});

process.on('uncaughtException', function(err) {
  console.error('An uncaught error occurred!');
  console.error(err.stack);
});
if("development" === app.get('env')) {
  app.use(function(req, res, next) {
    res.status(404).render("404", {
      title: "错误页面",
      content: "页面已丢失"
    });
  });
  app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).render("500", {
      title: "错误页面",
      content: "系统内部异常"
    });
  });
}

var port = 3666;

var server = http.createServer(app);

server.listen(port, function() {
  console.log('server is start,the port is: ' + port);
});